#!/usr/bin/env python3
"""
Retroid Pocket Mini Fan Service Daemon
Written for Batocera - @lbrpdx

In order to configure your own temperature/fan mapping
edit a file /userdata/system/configs/fan.conf with:

# temperatures are in Celsius
# fan_speed are from 0-100 percent of max speed
# syntax is: temp_threashold=fan_speed
# default is:
# 20=0
# 30=20
# 40=30
# 50=40
# 60=60
# 70=80
# 80=100

"""
import os
import time
import sys
import glob
from threading import Thread

DEBUG = 0
CHECK_INTERVAL = 15 # seconds between two temperature checks

config_file='/userdata/system/configs/fan.conf'

# Read fan % speed from the config file
def get_fanspeed(tempval, configlist):
    for curconfig in configlist:
        curpair = curconfig.split("=")
        tempcfg = float(curpair[0])
        fancfg = int(float(curpair[1]))
        if tempval >= tempcfg:
            return fancfg
    return 0

# Load the config file to memory
def load_config(fname):
    newconfig = []
    try:
        with open(fname, "r") as fp:
            for curline in fp:
                if not curline:
                    continue
                tmpline = curline.strip()
                if not tmpline:
                    continue
                if tmpline[0] == "#":
                    continue
                tmppair = tmpline.split("=")
                if len(tmppair) != 2:
                    continue
                tempval = 0
                fanval = 0
                try:
                    tempval = float(tmppair[0])
                    if tempval < 0 or tempval > 100:
                        continue
                except:
                    continue
                try:
                    fanval = int(float(tmppair[1]))
                    if fanval < 0 or fanval > 100:
                        continue
                except:
                    continue
                newconfig.append("{:5.1f}={}".format(tempval, fanval))
        if len(newconfig) > 0:
            newconfig.sort(reverse=True)
    except:
        return []
    return newconfig

# Check the current temperature and adjust fan speed
def temp_check():
    fanconfig = ["80=100", "70=80", "60=60", "50=40", "40=30", "30=20", "20=0"] # Default values when no config file
    tmpconfig = load_config(config_file)
    if len(tmpconfig) > 0:
        fanconfig = tmpconfig
    prevblock = 0
    fan_find = glob.glob("/sys/class/hwmon/hwmon*/pwm1")[0] 
    if not fan_find:
        print ("Error: no fan control found.")
        exit
    while True:
        with open("/sys/class/thermal/thermal_zone0/temp","r") as temp:
            tpp = temp.readline()
            val = float(int(tpp)/1000)
            block = get_fanspeed(val, fanconfig)
            if block < prevblock:
                time.sleep(CHECK_INTERVAL)
            prevblock = block
            try:
                num = int(block*2.55)
                if DEBUG:
                    print(f"Set fan speed {block}% ({num}) for temp {val}C ")
                with open(fan_find, "w") as fan_file:
                    fan_file.write("%i"%num)
            except IOError:
                temp = ""
            time.sleep(CHECK_INTERVAL)

# argument: start, stop, or no argument = show temp
if len(sys.argv)>1:
    if str(sys.argv[1]) == "start":
        try:
            t = Thread(target=temp_check)
            t.start()
        except Exception as e:
            print (f"Could not launch daemon: {e}")
            t.stop()
    elif str(sys.argv[1]) == "stop":
        try:
            # force fan stop
            fan_find = glob.glob("/sys/class/hwmon/hwmon*/pwm1")[0] 
            with open(fan_find, "w") as fan_file:
                fan_file.write("0")
        except Exception as e:
            print (f"Could not stop fan: {e}")
else:
    with open("/sys/class/thermal/thermal_zone0/temp","r") as tp:
        temp = tp.readline().strip()
        val = float(int(temp)/1000)
        print ("Temp: {:5.1f}C".format(val))

